/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lcfgly.util;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * <p>自定义加密算法。加密方式为一个byte与下一个byte相^.最后一个与keys里位于第一个byte数字的字符相^...
 *  结果用base64进行编码<br />
 * byte[x] re;<br />
 * re[x]=re[x]^re[x-1];<br />
 * re[re.length-1]=re[re.length-1]^keys[re[0]]</p>
 * @author lcfgly
 */
public class WybEncode {
    
    private static byte[] keys="%3#4S!4S0)$Y%%^&5(j.&^&o(*0)$Y%!".getBytes();
    

    public static String encode(String encode){
        if(encode == null)
            return "";
        try {
            byte[] re=encode.getBytes("utf8");
            int x=re.length;
            for (int i = 0; i < x; i++) {
//                System.out.println(re[i]);
                 re[i]^=(i+1<x?re[i+1]:keys[(re[0]+1)/8]);
//                if(i+1<x){
//                    re[i]^=re[i+1];
//                }else{
//                    System.out.println(re[i]+"=="+i+"=="+keys[(re[0]+1)/8]);
//                    re[i]^=keys[(re[0]+1)/8];
//                }
//                System.out.println(re[i]);
            }
            return Base64.encode(re).trim();
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(WybEncode.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }
    
    public static String decode(String decode){
        try {
            if(decode == null)
                return "";
            byte[] re=Base64.decode(decode);
            int x=re.length-1;
            boolean xe=true;
            for (; x>=0; x--){
//                System.out.println(re[x]);
//                System.out.println(key.indexOf((char)re[x]));
//                re[x]=(byte)key.indexOf((char)re[0]);
                re[x]^=xe?keys[(re[0]+1)/8]:re[x+1];
//                System.out.println(re[x]);
//                if(x==re.length-1){
//                    System.out.println(x+"=="+keys[(re[0]+1)/8]);
//                    re[x]^=keys[(re[0]+1)/8];
//                }else
//                    re[x]^=re[x+1];
//                System.out.println("||"+re[x]);
                xe=false;
            }
            return new String(re, "utf8");
        } catch (UnsupportedEncodingException ex) {
            return "";
        }
    }
    
}
